<template>
  <view class="custom-tabbar-wrap">
    <u-tabbar
      :value="current"
      @change="onChange"
      :fixed="true"
      :placeholder="true"
      :safe-area-inset-bottom="true"
      active-color="#1e90ff"
      inactive-color="#909399"
      :border="true"
    >
      <u-tabbar-item text="首页">
        <template #active-icon>
          <u-icon name="home-fill" size="26" color="#1e90ff"></u-icon>
        </template>
        <template #inactive-icon>
          <u-icon name="home" size="24" color="#909399"></u-icon>
        </template>
      </u-tabbar-item>

      <u-tabbar-item text="工作台">
        <template #active-icon>
          <u-icon name="grid-fill" size="26" color="#1e90ff"></u-icon>
        </template>
        <template #inactive-icon>
          <u-icon name="grid" size="24" color="#909399"></u-icon>
        </template>
      </u-tabbar-item>

      <u-tabbar-item text="我的">
        <template #active-icon>
          <u-icon name="account-fill" size="26" color="#1e90ff"></u-icon>
        </template>
        <template #inactive-icon>
          <u-icon name="account" size="24" color="#909399"></u-icon>
        </template>
      </u-tabbar-item>
    </u-tabbar>
  </view>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { useTabBarStore } from '@/stores/modules/tabbar'

const tabBarStore = useTabBarStore()

// 使用全局状态，所有页面的TabBar组件共享同一个状态
const current = computed(() => tabBarStore.currentIndex)

const tabList = [
  { path: '/pages/index/index' },
  { path: '/pages/document/dashboard/index' },
  { path: '/pages/profile/profile' },
]

const updateCurrent = () => {
  const pages = getCurrentPages()
  if (pages.length > 0) {
    const currentPage = pages[pages.length - 1]
    const route = '/' + currentPage.route
    const index = tabList.findIndex((item) => item.path === route)
    if (index !== -1) {
      tabBarStore.setCurrentIndex(index)
    }
  }
}

onShow(() => {
  updateCurrent()
})

const onChange = (index: number) => {
  // 立即更新全局状态，所有TabBar实例同步更新
  tabBarStore.setCurrentIndex(index)
  const path = tabList[index].path
  // 使用switchTab进行TabBar页面切换
  uni.switchTab({ url: path })
}
</script>

<style lang="scss" scoped>
// uview-plus的u-tabbar组件已经包含完整样式，无需额外定义
</style>
